
package com.reader.core.utils;
import com.reader.core.exception.CustomException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import java.util.Set;

/**
 * hibernate-validator校验工具类
 * @author jiahaikun
 * @since  2018-07-16 17:55
 */
public class ValidatorUtil {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    private static Validator validator;

    static {
        validator = Validation.buildDefaultValidatorFactory().getValidator();
    }

    /**
     * 校验对象
     * @param object        待校验对象
     * @param groups        待校验的组
     * @throws CustomException  校验不通过，CustomException
     */
    public static void validateEntity(Object object, Class<?>... groups) throws CustomException {
        Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object, groups);
        if (!constraintViolations.isEmpty()) {
        	ConstraintViolation<Object> constraint =constraintViolations.iterator().next();
            throw new CustomException(constraint.getMessage());
        }
    }
}
